//
//  XJYChatData.m
//  高仿萝卜书摘
//
//  Created by 谢俊逸 on 06/12/2016.
//  Copyright © 2016 谢俊逸. All rights reserved.
//

#import "XJYChatData.h"
#import "NSUserDefaults+DemoSettings.h"
#import <ChatKit/LCChatKit.h>
#import <AVIMClient.h>
#import "XJYHeader.h"


@interface XJYChatData ()<AVIMClientDelegate>
@property (nonatomic,strong) AVIMClient *client;

@property (nonatomic,strong) void(^setupJSQMessagesBlock)();
@end
@implementation XJYChatData

- (instancetype)init{
    self = [super init];
    if (self) {
#pragma mark Notification
        
//        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMessage) name:@"DidReceiveMessage" object:nil];
      
        JSQMessagesAvatarImageFactory *avatarFactory = [[JSQMessagesAvatarImageFactory alloc] initWithDiameter:kJSQMessagesCollectionViewAvatarSizeDefault];
        
        JSQMessagesAvatarImage *jsqImage = [avatarFactory avatarImageWithUserInitials:@"JSQ"
                                                                      backgroundColor:[UIColor colorWithWhite:0.85f alpha:1.0f]
                                                                            textColor:[UIColor colorWithWhite:0.60f alpha:1.0f]
                                                                                 font:[UIFont systemFontOfSize:14.0f]];
        
        JSQMessagesAvatarImage *cookImage = [avatarFactory avatarImageWithImage:[UIImage imageNamed:@"demo_avatar_cook"]];
        
        JSQMessagesAvatarImage *jobsImage = [avatarFactory avatarImageWithImage:[UIImage imageNamed:@"demo_avatar_jobs"]];
        
        JSQMessagesAvatarImage *wozImage = [avatarFactory avatarImageWithImage:[UIImage imageNamed:@"demo_avatar_woz"]];
        
        self.avatars = @{ kJSQDemoAvatarIdSquires : jsqImage,
                          kJSQDemoAvatarIdCook : cookImage,
                          kJSQDemoAvatarIdJobs : jobsImage,
                          kJSQDemoAvatarIdWoz : wozImage };
        
        
        self.users = @{ kJSQDemoAvatarIdJobs : kJSQDemoAvatarDisplayNameJobs,
                        kJSQDemoAvatarIdCook : kJSQDemoAvatarDisplayNameCook,
                        kJSQDemoAvatarIdWoz : kJSQDemoAvatarDisplayNameWoz,
                        kJSQDemoAvatarIdSquires : kJSQDemoAvatarDisplayNameSquires };
        
        

        JSQMessagesBubbleImageFactory *bubbleFactory = [[JSQMessagesBubbleImageFactory alloc] init];
        
        self.outgoingBubbleImageData = [bubbleFactory outgoingMessagesBubbleImageWithColor:[UIColor jsq_messageBubbleLightGrayColor]];
        self.incomingBubbleImageData = [bubbleFactory incomingMessagesBubbleImageWithColor:[UIColor jsq_messageBubbleGreenColor]];

        self.client = self.client;
    }
    return self;
}


- (void)setupMessages{
    
    

    
}
- (void)queryMessage{
    
    [self.client openWithCallback:^(BOOL succeeded, NSError *error) {
        // Tom 创建查询会话的 query
        AVIMConversationQuery *query = [self.client conversationQuery];
        // Tom 获取 id 为 2f08e882f2a11ef07902eeb510d4223b 的会话
        [query getConversationById:self.conversation.conversationId callback:^(AVIMConversation *conversation, NSError *error) {
            // 查询对话中最后 10 条消息
            [conversation queryMessagesWithLimit:10 callback:^(NSArray *objects, NSError *error) {
                self.messages = (NSMutableArray *)objects;
                NSLog(@"查询成功！");
                [objects enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    AVIMMessage *aviMessage = objects[idx];
                    JSQMessage *jsqMessage = [[JSQMessage alloc]initWithSenderId:aviMessage.clientId senderDisplayName:aviMessage.clientId  date:[NSDate date] text:aviMessage.content];
                    _messages[idx] = jsqMessage;
                }];
                self.messagesChangeBlock();
            }];
        }];
    }];
}



#pragma mark 懒加载

- (AVIMClient *)client{
    
    if (!_client) {
        NSUserDefaults *standUserDefaults = [NSUserDefaults standardUserDefaults];
        NSDictionary *userData = [standUserDefaults objectForKey:kLoginUserDict];
        
        _client = [[AVIMClient alloc]initWithClientId:userData[@"name"]];
        
        //委托
        _client.delegate = self;
        [_client openWithCallback:^(BOOL succeeded, NSError *error) {
            NSLog(@"打开成功Client");
            [self queryMessage];

#pragma mark 数据查询
        }];
    }
    return _client;
}


#pragma mark 增加聊天数据
- (void)addMessages:(JSQMessage *)message{
    [self.messages addObject:message];
    AVIMMessage *aviMessage = [AVIMTextMessage messageWithText:message.text attributes:nil];
#pragma mark 在这里向服务器发送数据
    [self.client openWithCallback:^(BOOL succeeded, NSError *error) {
       [self.conversation sendMessage:aviMessage options:AVIMMessageSendOptionRequestReceipt callback:^(BOOL succeeded, NSError *error) {
           if (succeeded) {
               NSLog(@"发送成功");
           }else{
               //这里可以做消息发送失败的block
               NSLog(@"error == %@",error);
               [self.messages removeObject:message];
           }
       }];
    }];
}



#pragma mark - AVIMClientDelegate

// 接收消息的回调函数
- (void)conversation:(AVIMConversation *)conversation didReceiveTypedMessage:(AVIMTypedMessage *)message{
    NSLog(@"别人发送我接收成功,TypeMessage");
    [self queryMessage];
}

- (void)conversation:(AVIMConversation *)conversation didReceiveCommonMessage:(AVIMMessage *)message{
    NSLog(@"别人发送我接收成功,CommonMessage");
    [self queryMessage];
}

- (void)conversation:(AVIMConversation *)conversation messageDelivered:(AVIMMessage *)message{
    NSLog(@"%@", @"消息已送达。"); // 打印消息
}
- (void)conversation:(AVIMConversation *)conversation didReceiveUnread:(NSInteger)unread {
    // unread 是未读消息数量，conversation 为所属的会话
    // 没有未读消息就跳过
    NSLog(@"333");
    if (unread <= 0) return;
    
    // 否则从服务端取回未读消息
    [conversation queryMessagesFromServerWithLimit:unread callback:^(NSArray *objects, NSError *error) {
        
        NSLog(@"1212121212");
        if (!error && objects.count) {
            // 显示消息或进行其他处理
            //刷新messages数组
            NSUInteger count = self.messages.count;
            [objects enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                AVIMMessage *aviMessage = objects[idx];
                JSQMessage *jsqMessage = [[JSQMessage alloc]initWithSenderId:aviMessage.clientId senderDisplayName:aviMessage.clientId  date:[NSDate date] text:aviMessage.content];
                _messages[count + idx] = jsqMessage;
            }];
            //刷新界面数据
            self.messagesChangeBlock();
        }
        
    }];
    // 将这些消息标记为已读
    [conversation markAsReadInBackground];
}

#pragma mark Notification 
//- (void)didReceiveMessage{
//    [self queryMessage];
//}

@end
